package togoogle;

import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import javax.jdo.PersistenceManager;
import java.util.Map;
import java.util.logging.Logger;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xml.sax.InputSource;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.sample.structuredcontent.basicexample.StructuredContentSample;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.domain.Item;
import com.taobao.api.request.ItemsListGetRequest;
import com.taobao.api.response.ItemsListGetResponse;


import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
import togoogle.common.Constant;
import togoogle.common.Util;

@Controller
public class getproductcontroller {
	private static final Logger log = Logger.getLogger("Main"); 

        @RequestMapping(value = "/togoogle/getproduct",method = RequestMethod.GET)
        public String doGet(String top_appkey, String top_session, 
        		            String top_parameters,String top_sign,Model model) throws IOException {
        	String sql="select from "+productinfo.class.getName();
        	PersistenceManager pm = PMF.get().getPersistenceManager();
        	List<productinfo> productinfos=null;
        	try {
              productinfos = (List<productinfo>) pm.newQuery(sql).execute();
              if(productinfos==null || productinfos.size()==0)
            	  return "getproduct";
            } catch(Exception e) {
              pm.close();
              return "getproduct";
            }
        	String prodids="";
        	String items="";
        	int pronum=0;
        	Iterator itr = productinfos.iterator();
        	while(itr.hasNext()){
        		productinfo p=(productinfo) itr.next();
        		prodids=prodids+p.getProductId()+",";
        		if(++pronum%20==0){	
        			prodids=prodids.substring(0, prodids.length()-1);
        			log.info("productids:"+prodids);
        			String fields="detail_url,num_iid,title,desc,pic_url,num,price";
        			ItemsListGetRequest request=new ItemsListGetRequest();
        			ItemsListGetResponse respons=null;
        			request.setFields(fields);
        			request.setNumIids(prodids);
        			request.setTimestamp((new Date()).getTime());
        			DefaultTaobaoClient cli=new DefaultTaobaoClient(Constant.SANDBOX_URL, Constant.APP_KEY, Constant.APP_SERCET);
        			try {
        				respons=cli.execute(request);
        				if(respons==null || !respons.isSuccess()){
        					log.info(respons.getBody());
        					return "error";
        				}
        			} catch (ApiException e) {
        				// TODO Auto-generated catch block
        				log.info(e.getErrMsg());
        				return "error";
        			}
        			List<Item> listitems=respons.getItems();

        			for(int i=0;i<listitems.size();i++){
        				Item item=listitems.get(i);
        				String avail="out of stock";
        				String postfee=item.getPostFee();
        				String DetailUrl="http://taokegoo.appspot.com/togoogle/geturl?page=detail&productid="+item.getNumIid();
        				String ImgUrl="http://taokegoo.appspot.com/togoogle/geturl?page=img&productid="+item.getNumIid();
        				if(item.getNum()>=0)
        					avail="in stock";
        				if(postfee==null)
        					postfee="0.0";
        				String tmp=DetailUrl+"\t"+item.getNumIid()+"\t"+item.getTitle()+"\t"
        							+item.getTitle()+"\t"+ImgUrl+"\t"+avail+"\t"+item.getPrice()+"CNY\t"
        							+postfee+"CNY"+"\t"+"new";
        				items=items+tmp+"\n";
        				//log.info(items);
        			}
        			prodids="";
        		}
        	}
        	/*try{
        		FtpClient ftpclient=new FtpClient(Constant.FTP_URL, 21);
            	ftpclient.login(Constant.USR_NAME, Constant.PASSWD);
            	ftpclient.cd("/");
            	ftpclient.binary();
            	TelnetOutputStream ftpOut = ftpclient.put("data_feed.txt");
            	ftpOut.write(items.getBytes(), 0, items.length());
            	ftpOut.close();
        	}catch(Exception e){
        		log.info(e.getMessage());
        	}
        	*/
        	model.addAttribute("items", items);
        	return "getproduct";
        }
}